
import SpriteKit

extension SKSpriteNode{
    func move(by velocity:CGPoint,in dt:TimeInterval){
        let amountToMove = CGPoint(x: velocity.x * CGFloat(dt), y: velocity.y * CGFloat(dt))
        position.x += amountToMove.x
        position.y += amountToMove.y
    }
}

class GameScene:SKScene{
    
    var zombie:SKSpriteNode!
    var lastUpdateTime:TimeInterval = 0
    var dt:TimeInterval = 0
    
    let playableRect:CGRect
    
    let zombieMovePointsPerSec:CGFloat = 480.0
    var velocity = CGPoint.zero
    
    override init(size: CGSize) {
        let maxAspectRatio:CGFloat = 16.0/9.0 // 1
        let playableHeight = size.width / maxAspectRatio // 2
        let playableMargin = (size.height-playableHeight)/2.0 // 3
        playableRect = CGRect(x: 0, y: playableMargin,
                              width: size.width,
                              height: playableHeight) // 4
        super.init(size: size) // 5
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    /*
    override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
        guard let touch = touches.first else {
            return
        }
        
        let touchLocation = touch.location(in: self)
        moveToward(zombie: zombie, location: touchLocation)
    }
    
    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        guard let touch = touches.first else {
            return
        }
        
        let touchLocation = touch.location(in: self)
        moveToward(zombie: zombie, location: touchLocation)
    }*/
    
    
    
    func moveToward(zombie:SKSpriteNode, location:CGPoint){
        let offset = CGPoint(x: location.x - zombie.position.x, y: location.y - zombie.position.y)
        let length = sqrt(Double(offset.x * offset.x + offset.y * offset.y))
        let direction = CGPoint(x: offset.x/CGFloat(length), y: offset.y/CGFloat(length))
        velocity = CGPoint(x: direction.x * zombieMovePointsPerSec, y: direction.y * zombieMovePointsPerSec)
    }
    
    override func update(_ currentTime: TimeInterval) {
        
        if lastUpdateTime > 0{
            dt = currentTime - lastUpdateTime
        }else{
            dt = 0
        }
        lastUpdateTime = currentTime
        print("\(dt * 1000) ms since laset updte")
        
        zombie.move(by: velocity, in: dt)
        
        boundsCheckZombie()
    }
    
    @objc func tap(g:UITapGestureRecognizer){
        let viewLocation = g.location(in: self.view)
        let touchLocation = convertPoint(fromView: viewLocation)
        moveToward(zombie: zombie, location: touchLocation)
    }
    
    @objc func pan(g:UIPanGestureRecognizer){
        let viewLocation = g.location(in: self.view)
        let touchLocation = convertPoint(fromView: viewLocation)
        moveToward(zombie: zombie, location: touchLocation)
    }
    
    func boundsCheckZombie() {
        //let scale = UIApplication.shared.keyWindow?.screen.scale
        let bottomLeft = CGPoint(x: 0, y: playableRect.minY)
        let topRight = CGPoint(x: size.width, y: playableRect.maxY)
        //print("topRight is \(topRight)")
        //print("viewBounds is \(view?.bounds.size)")
        if zombie.position.x <= bottomLeft.x {
            zombie.position.x = bottomLeft.x
            velocity.x = -velocity.x
        }
        if zombie.position.x >= topRight.x {
            zombie.position.x = topRight.x
            velocity.x = -velocity.x
        }
        if zombie.position.y <= bottomLeft.y {
            zombie.position.y = bottomLeft.y
            velocity.y = -velocity.y
        }
        if zombie.position.y >= topRight.y {
            zombie.position.y = topRight.y
            velocity.y = -velocity.y
        }
    }
    
    func debugDrawPlayableArea() {
        let shape = SKShapeNode()
        let path = CGMutablePath()
        path.addRect(playableRect)
        shape.path = path
        shape.strokeColor = SKColor.red
        shape.lineWidth = 4.0
        addChild(shape)
    }
    
    override func didMove(to view: SKView) {
        backgroundColor = .black
        
        let bg = SKSpriteNode(imageNamed: "background1")
        bg.anchorPoint = .zero
        bg.zPosition = -1
        self.addChild(bg)
        
        zombie = SKSpriteNode(imageNamed: "zombie1")
        zombie.position = CGPoint(x: 400, y: 400)
        addChild(zombie)
        
        let tap = UITapGestureRecognizer(target: self, action: #selector(self.tap(g:)))
        view.addGestureRecognizer(tap)
        
        debugDrawPlayableArea()
        //let pan = UIPanGestureRecognizer(target: self, action: #selector(self.pan(g:)))
        //view.addGestureRecognizer(pan)
    }
}
